<?php

namespace App\Http\Controllers\Mobile;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\UCenterController;

class CostomerController extends Controller
{
	//客户个人中心我的订阅   
    public function followmanagement(Request $request){
    	$id           = intval(trim($request->id));
        $mefollowdata = myselfSubAnalyst($id);
        $info         = memberInfo($id);
        $sessiondata  = $request->session()->get('eai');
        if($sessiondata['id'] == $id){
            $isself = 1;
        }else{
            $isself = 0;
        }
    	return view('mobile.management',compact('mefollowdata','info','isself'));
    }
    //分析师我的策略
    public function myhandan(Request $request){
    	$id   = intval(trim($request->userid));
        $info = memberInfo($id);
    	return view('mobile.fmyhandan',compact('info'));
    }
    //榜单进去分析师我的策略
    public function fhandan(Request $request){
    	$id   = intval(trim($request->analyst_id));
        $info = memberInfo($id);
    	return view('newmobile.masterlist',compact('info'));
    }
    //客户个人中心我的策略
    public function kmyhandan(Request $request){
    	$id   = intval(trim($request->userid));
        $info = memberInfo($id);
    	return view('mobile.kmyhandan',compact('info'));
    }
    //分析师订阅评论
    public function followcomment(){
    	return view('mobile.fcomment',compact('info'));
    }
    //分析师数据统计
    public function mydatacount(Request $request){
    	$id             = intval(trim($request->userid));
    	$info           = memberInfo($id);
    	$usertel        = $info[0] -> tel;
    	$memdeltype     = memDelType($usertel); //交易品种
    	$memadepttype   = memAdeptType($usertel,5); //擅长品种 
    	$totaldeal      = memTotalReport($usertel); //总交易报表
    	$memorderinfo   = memOrderInfo($usertel); //用户有关信息
    	//交易品种
    	if($memdeltype){
        	foreach($memdeltype['ordernum'] as $k=>$v){
        		$typename[] = '{"value":"'.$memdeltype['ordernum'][$k].'","name":"'.$memdeltype['typeenname'][$k].'"}';
        	}
            $typenamestr = implode(',',$typename);
        }else{
            $typenamestr = '';
        }
        //总交易报表
        if($totaldeal){
            $timeDayJiaoyi = implode(',',$totaldeal['day']);
            $pointDayJiaoyi = implode(',',$totaldeal['totalpoint']);
        }else{
            $timeDayJiaoyi = '';
            $pointDayJiaoyi = '';
        }
    	return view('mobile.analystdata',compact('memdeltype','info','typenamestr','memadepttype','timeDayJiaoyi','pointDayJiaoyi','memorderinfo'));
    }
    //分析师我的订阅
    public function kgendan(Request $request){
        $id   = intval(trim($request->id));
        $info = memberInfo($id);
        $mefollowdata = myselfSubAnalyst($id);
        $sessiondata  = $request->session()->get('eai');
        if($sessiondata['id'] == $id){
            $isself = 1;
        }else{
            $isself = 0;
        }
//      dd($mefollowdata);
        return view('newmobile.kdingyuejilu',compact('mefollowdata','info','isself'));
    }
    //设置
    public function setup(Request $request){
        $id   = intval(trim($request->id));
        $info = memberInfo($id);
//      $mefollowdata = myselfSubAnalyst($id);
        return view('mobile.setup',compact('info'));
    }
    //分析师认证
    public function certify(Request $request){
    	$sessionData = $request->session()->get('eai');
        if(!$sessionData){
            return redirect('mlogin');
        }
    	$userinfo = DB::table('waihui_member')->select('*')->where('id','=',$sessionData['id'])->first();
    	if(!$userinfo){
            return redirect('bdlists');
        }else{
           $authinfo    = DB::table('waihui_member_info')->where(array('userid'=>$sessionData['id']))->first(); //认证信息
        }
     // dd($userinfo);
    	return view('mobile.analystcertify',compact('authinfo','userinfo'));
    }
    //提现管理
    public function withdrawals(Request $request){
    	$sessionData  = $request->session()->get('eai');
        if(!$sessionData){
            return redirect('mlogin');
        }
        $allowweekbonus  = DB::table('waihui_active_ranking')
                            ->select(DB::raw("SUM(actual_bonus) AS totalbonus"))
                            ->where(array('userid'=>$sessionData['id'],'status'=>2,'draw_status'=>1))
                            ->get()->toArray();//周赛达标 未领取金额
        $totalweekbonus  = DB::table('waihui_active_ranking')
                                ->select(DB::raw("SUM(actual_bonus) AS totalbonus"))
                                ->where(array('userid'=>$sessionData['id'],'status'=>2))
                                ->get()->toArray();//周赛达标 总金额
        $yetweekbonus    = $totalweekbonus[0]->totalbonus - $allowweekbonus[0]->totalbonus; //周赛达标 已领取金额
        $where['tel']          = $sessionData['tel'];
        $where['ispersonal']   = 0;
        $where['isstop']       = 0;
        $where['trade_status'] = '1';
        //策略 总盈利信息
        $allmonthsmoney = DB::table('waihui_order')
                            ->select(DB::raw("sum(money) as money"),DB::raw("FROM_UNIXTIME(end_time, '%Y年%m月') AS months"))
                            ->where($where)->where('money','>',0)->orderBy('end_time','desc')->groupBy('months')->get()->toArray();
        //策略 已领取信息
        $yetmonthsmoney = DB::table('waihui_withdraw')->select('money','draw_id')
                            ->where([['type','=',2],['userid','=',$sessionData['id']]])->get()->toArray();
        //策略 总盈利金额
        $totalmonthsmoney = 0;
        foreach ($allmonthsmoney as $akey=>$aval){
            $totalmonthsmoney = $totalmonthsmoney+$aval->money;
        }
        //策略 已领取金额
        $yettotalmonthsmoney = 0;
        foreach ($yetmonthsmoney as $ykey=>$yval){
            $yettotalmonthsmoney = $yettotalmonthsmoney+$yval->money;
        }
        //策略 未领取金额
        if($totalmonthsmoney){
            $allowmonthsmoneys    = $totalmonthsmoney-$yettotalmonthsmoney;
        }else{
            $allowmonthsmoneys    = 0;
        }
    	return view('mobile.withdrawals',compact('allowweekbonus','totalweekbonus','yetweekbonus','totalmonthsmoney','yettotalmonthsmoney','allowmonthsmoneys'));
    }
    //交易大师中心总览
    public function masterCenter(Request $request){
    	$id   = intval(trim($request->analyst_id));
        $info = memberInfo($id);
    	$usertel        = $info[0] -> tel;
    	$totaldeal      = memTotalReport($usertel); //总交易报表
    	$memorderinfo  = memOrderInfo($usertel); //用户有关信息
       
       // $memorderinfo[0]->gray = 100-$memorderinfo[0]->winrate;
       //dd($memorderinfo);
    	//交易品种
        //总交易报表
        if($totaldeal){
            $timeDayJiaoyi = implode(',',$totaldeal['day']);
            $pointDayJiaoyi = implode(',',$totaldeal['totalpoint']);
        }else{
            $timeDayJiaoyi = '';
            $pointDayJiaoyi = '';
        }
        $userc    = new UCenterController();
        //总交易，做多交易和做空交易
        $delproit = $userc->allTrade($usertel); 
        //最大连胜，最大连亏,最大涨幅，最大回撤
        $maxdata  = UCenterController::maxDada($usertel);
        //稳定值,查询最近两周的
        $wendata  = UCenterController::wenDindZhi($usertel);
        $session_data = $request->session()->get('eai');
        //订阅状态
        $followstatus = 0;
        if($session_data){
            $followinfo  = DB::table('waihui_follow')->where([['analyst_id','=',$id],['follower_id','=',$session_data['id']]])->first();
            if($followinfo){
                $followstatus= $followinfo->status;
            }else{
                $followstatus= 0; //未订阅 或 取消订阅的状态
            }
        }
        if($session_data['id'] == $id){
            $followstatus = 2; //是我自己不显示按钮
        }
    	return view('newmobile.mastercenter',compact('id','info','timeDayJiaoyi','pointDayJiaoyi','memorderinfo','delproit','maxdata','wendata','followstatus'));
    }
    //持仓
    public function chicang(Request $request){
        $session_data = $request->session()->get('eai');

        if($session_data){  // 获取用户当前持仓单
            $chicangNum = 0;
            $typenames = []; //当前用户所订阅的分析师持仓的品种
            $where=array('follower_id'=>$session_data['id'],'status'=>1);   
            $analystData = DB::table('waihui_follow as f') //查询出用户订阅的分析师
                         ->join('waihui_member as m','m.id','f.analyst_id')
                         ->select('analyst_id','analyst_name',DB::raw('FROM_UNIXTIME(follow_time,"%y-%m-%d") as follow_time'),'m.tel','m.username','m.photo','m.isanalyst')
                         ->where($where)->get()->toArray();
            foreach($analystData as $k=>$v){ //查询出这些分析师的持仓单子
                $analystData[$k]->list = DB::table('waihui_order as o')
                                        ->join('waihui_member as m','m.tel','o.tel')
                                        ->join('waihui_type as t','o.typename','t.name')
                                        ->select('t.chinaname','o.tradeid','o.typename','o.buy_status',DB::raw('FROM_UNIXTIME(o.begin_time,"%y-%m-%d %H:%i:%s") as begin_time'),'o.begin_point','o.profit_point','o.loss_point','o.target_profit_point','o.target_loss_point','o.baosun')
                                        ->where([['isstop','=',1],['ispersonal','=',0],['o.tel','=',$v->tel]])->get()->toArray();
                if(count($analystData[$k]->list) == 0){ 
                    unset($analystData[$k]);
                }else{
                    $chicangNum += count($analystData[$k]->list);
                    foreach ($analystData[$k]->list as $t=>$y){
                        $typenames[] = 'FX'.$y->typename;
                    }
                    //订阅状态
                    if($session_data){
                        $followinfo  = DB::table('waihui_follow')->where([['analyst_id','=',$v->analyst_id],['follower_id','=',$session_data['id']]])->first();
                        if($followinfo){
                            $analystData[$k]->followstatus= $followinfo->status;
                        }else{
                            $analystData[$k]->followstatus= 0; //未订阅 或 取消订阅的状态
                        }
                    }else{
                        $analystData[$k]->followstatus = 0;
                    }
                }
            }
            $typenames = array_unique($typenames); //去除重复的品种
            $typenames = implode(',', $typenames);
        }else{
            return redirect('mlogin');
        }
        $starttime  = strtotime(date("Y-m-d H:i:s",mktime(5,0,0,date("m"),date("d")-date("w")+(date("w")==0?-6:1),date("Y")))); //周一早上5:00:00
        $endtime    = strtotime(date("Y-m-d H:i:s",mktime(5,0,0,date("m"),date("d")-date("w")+(date("w")==0?-1:6),date("Y")))); //周六早上5:00:00
//        $userid = $session_data['id'];
////        return view('mobile.chicang',compact('return','starttime','endtime','alltype','sumfinal','userid'));
        return view('newmobile.chicang',compact('analystData','chicangNum','starttime','endtime','typenames','followstatus'));
    }
    //设置
    public function echarts(Request $request){
        $starttime  = strtotime(date("Y-m-d H:i:s",mktime(5,0,0,date("m"),date("d")-date("w")+(date("w")==0?-6:1),date("Y")))); //周一早上5:00:00
        $endtime    = strtotime(date("Y-m-d H:i:s",mktime(5,0,0,date("m"),date("d")-date("w")+(date("w")==0?-1:6),date("Y")))); //周六早上5:00:00
        return view('mobile.echarts',compact('starttime','endtime'));
    }
     public function news(Request $request){
//            return view('mobile.news');
            return view('newmobile.news');
     }
     //注册协议
     public function registeroder(Request $request){
         return view('mobile.registeroder');
     }
    //交易行为
    public function jyXingWei(Request $request){
        $session_data = $request->session()->get('eai');
        $id   = intval(trim($request->analyst_id));
        $info = memberInfo($id);
        $usertel        = $info[0] -> tel;
        $memdeltype     = memDelType($usertel); //交易品种
        $memadepttype   = memAdeptType($usertel,5); //擅长品种
        if($memdeltype){
              foreach($memdeltype['ordernum'] as $k=>$v){
                  $typename[] = '{"value":"'.$memdeltype['ordernum'][$k].'","name":"'.$memdeltype['typeenname'][$k].'"}';
              }
             $typenamestr = implode(',',$typename);
         }else{
             $typenamestr = '';
         }
         //盈亏图
        $userc         =  new UCenterController();
        $plarr         = $userc->profitLoss($usertel);
        $pltimestr     = $plarr[0];
        $plpointstr    = $plarr[1];
        $profitpointstr= $plarr[2];
        $losspointstr  = $plarr[3];
        //下单时间分布图
        $deltimemap   = $userc->delTimeMap($usertel);
        $delpointstr  = $deltimemap[0];
        $deltimetstr  = $deltimemap[1];
        $delwinratestr= $deltimemap[2];
        //点位区间图
        $pointBetweenChat = $userc->pointBetweenChat($usertel);
        //查询用户擅长短线，中线还是长线交易
        $LineAndPoint = $userc->linePoint($usertel);
        $lastPoint = json_decode($LineAndPoint);
        //订阅状态
        $followstatus = 0;
        if($session_data){
            $followinfo  = DB::table('waihui_follow')->where([['analyst_id','=',$id],['follower_id','=',$session_data['id']]])->first();
            if($followinfo){
                $followstatus= $followinfo->status;
            }else{
                $followstatus= 0; //未订阅 或 取消订阅的状态
            }
        }
        if($session_data['id'] == $id){
            $followstatus = 2; //是我自己不显示按钮
        }
        return view('newmobile.jyXingWei',compact('id','memdeltype','typenamestr','memadepttype','pltimestr','plpointstr','profitpointstr','losspointstr','delpointstr','deltimetstr','delwinratestr','pointBetweenChat','lastPoint','followstatus'));
    }
    //客户的数据分析
    public function dataFenXi(Request $request){
        $id   = intval(trim($request->id));
        $info = memberInfo($id);
        $usertel        = $info[0] -> tel;
        //收益曲线图
        $DayJiaoyi      = memGendanReport($usertel);
        $timeDayJiaoyi  = implode(',',$DayJiaoyi['day']);
        $pointDayJiaoyi = implode(',',$DayJiaoyi['totalpoint']);
        //总收益，正向收益，方向收益
        $data = DB::table('waihui_gendan as g')
                    ->join('waihui_order as o','g.tradeid','o.tradeid')
                    ->select(DB::raw('Round(SUM(o.end_point-o.begin_point),2) as allpoint'),DB::raw('Round(SUM(case g.direction when 0 then o.final_point end),2) zxprofit'),DB::raw('Round(SUM(case g.direction when 1 then o.final_point end),2) fxprofit'))
                    ->where([['g.follower_tel','=',$usertel],['g.isstop','=',0],['g.ispersonal','=',0]])
                    ->get()
                    ->toArray();
        //历史订阅数
        $dingyuenum = DB::table('waihui_follow')->where([['follower_id','=',$id],['status','=',0]])->count();
        return view('newmobile.dataFenXi',compact('timeDayJiaoyi','pointDayJiaoyi','data','dingyuenum'));
    }
}
